#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define N 2
#define NUM 1024
using namespace std;

void Writer(int wfd)
{
    string s="hello,i am child";
    pid_t self=getpid();
    int num=0;

    char buf[NUM];  
    while(true)
    {
        //构建发送字符串，把如上三条信息存放到该数组
        buf[0]=0;           //清空缓冲区字符串，用这个数组存放字符串 

        snprintf(buf,sizeof(buf),"%s-%d-%d",s.c_str(),self,num++);          
        
        //打印观察是否符合预期
        //cout<<buf<<endl;

        //发送给父进程，而不是显示到屏幕
        write(wfd,buf,strlen(buf));     //文件描述符，字符串，个数，把XX位个数的字符串写入到描述符 
        sleep(1);
    }
}

void Reader(int rfd)
{
    char buf[NUM];
    while(true)
    {
        buf[0]=0;
        ssize_t n=read(rfd,buf,sizeof(buf));
        if(n>0) 
        {
            buf[n]=0;       //给字符串末尾填结束标志'\0'

            //显示打印  
            cout<<"father get a message["<<getpid()<<"]#"<<buf<<endl;
        }
    }

}
int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0) return 1;
    
    //检测管道是否正确创建 
    // cout<<"pipefd[0]:"<<pipefd[0]<< ",pipefd[1]:"<<pipefd[1]<<endl;
   
    //让子进程写，父进程读
     pid_t id = fork();
     if(id<0) return 2;
     if(id==0)
     {
        //子进程写，就关闭读
        close(pipefd[0]);
        
        //写内容，调用函数
        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
     }

     //父进程读，就关闭写
    close(pipefd[1]);

    //读内容，调用函数
    Reader(pipefd[0]);

    pid_t rid=waitpid(id,nullptr,0);
    if(rid<0) return 3;

    close(pipefd[0]);
    return 0;
}
